package com.hh.flow.controller;

import cn.hutool.core.util.StrUtil;
import com.hh.common.constant.HttpStatus;
import com.hh.common.core.domain.R;
import com.hh.common.core.page.PageDomain;
import com.hh.common.core.page.TableDataInfo;
import com.hh.common.core.page.TableSupport;
import com.hh.common.utils.ExceptionUtil;
import com.hh.common.utils.MessageUtils;
import com.hh.flow.service.ExecuteService;
import com.hh.log.annotaion.Log;
import com.hh.log.enums.BusinessType;
import com.hh.mybatisflex.controller.BaseController;
import com.hh.system.api.ISysUserService;
import com.hh.system.api.domain.SysUser;
import com.monkey.flow.core.webService.HisTaskAppService;
import com.monkey.flow.core.webService.InsAppService;
import com.monkey.flow.core.webService.TaskAppService;
import com.monkey.flow.core.domain.entity.FlowHisTask;
import com.monkey.flow.core.domain.entity.FlowTask;
import com.monkey.mybatis.core.page.Page;
import com.monkey.mybatis.core.utils.PageUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 流程实例Controller
 *
 * @author hh
 * @date 2023-04-18
 */
@Validated
@RestController
@RequestMapping("/flow/execute")
public class ExecuteController extends BaseController
{
    @Resource
    private ExecuteService executeService;

    @Resource
    private InsAppService insAppService;

    @Resource
    private HisTaskAppService hisTaskAppService;

    @Resource
    private TaskAppService taskAppService;

    @Resource
    private ISysUserService userService;

    /**
     * 分页待办任务列表
     */
    @PreAuthorize("@ss.hasPermi('flow:execute:toDoPage')")
    @GetMapping("/toDoPage")
    public TableDataInfo<FlowTask> toDoPage(FlowTask flowTask)
    {
        try {
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Page<FlowTask> page = PageUtil.getPage(pageDomain.getPageNum(), pageDomain.getPageSize());
            page = taskAppService.getService().toDoPage(flowTask, page);
            page.getList().forEach(instance -> {
                if (StrUtil.isNotBlank(instance.getApprover())){
                    SysUser sysUser = userService.selectUserById(Long.valueOf(instance.getApprover()));
                    instance.setApprover(sysUser.getNickName());
                }
            });
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(page.getList());
            rspData.setTotal(page.getTotal());
            return rspData;
        } catch (Exception e) {
            String msg = MessageUtils.message("controller.page");
            logger.error(msg, e);
            return TableDataInfo.fail(ExceptionUtil.handleMsg(msg, e));
        }
    }

    /**
     * 分页已办任务列表
     */
    @PreAuthorize("@ss.hasPermi('flow:execute:donePage')")
    @GetMapping("/donePage")
    public TableDataInfo<FlowHisTask> donePage(FlowHisTask flowHisTask)
    {
        try {
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Page<FlowHisTask> page = PageUtil.getPage(pageDomain.getPageNum(), pageDomain.getPageSize());
            page = hisTaskAppService.getService().donePage(flowHisTask, page);
            page.getList().forEach(hisTask -> {
                if (StrUtil.isNotBlank(hisTask.getApprover())){
                    SysUser sysUser = userService.selectUserById(Long.valueOf(hisTask.getApprover()));
                    hisTask.setApprover(sysUser.getNickName());
                }
            });
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(page.getList());
            rspData.setTotal(page.getTotal());
            return rspData;
        } catch (Exception e) {
            String msg = MessageUtils.message("controller.page");
            logger.error(msg, e);
            return TableDataInfo.fail(ExceptionUtil.handleMsg(msg, e));
        }
    }

    /**
     * 查询已办任务历史记录
     */
    @PreAuthorize("@ss.hasPermi('flow:execute:doneList')")
    @GetMapping("/doneList/{instanceId}")
    public R<List<FlowHisTask>> doneList(@PathVariable("instanceId") Long instanceId)
    {
        FlowHisTask flowHisTask = new FlowHisTask();
        flowHisTask.setInstanceId(instanceId);
        try {
            List<FlowHisTask> flowHisTasks = hisTaskAppService.getService().list(flowHisTask);
            flowHisTasks.forEach(hisTask -> {
                if (StrUtil.isNotBlank(hisTask.getApprover())){
                    SysUser sysUser = userService.selectUserById(Long.valueOf(hisTask.getApprover()));
                    hisTask.setApprover(sysUser.getNickName());
                }
            });
            return R.ok(flowHisTasks);
        } catch (Exception e) {
            String msg = "查询已办任务历史记录失败！";
            logger.error(msg, e);
            return R.fail(msg);
        }
    }

    /**
     * 办理
     */
    @PreAuthorize("@ss.hasPermi('flow:execute:handle')")
    @Log(title = "流程实例", businessType = BusinessType.OTHER)
    @GetMapping("/handle")
    public R handle(Long id, String conditionValue, String message)
    {
        try {
            return R.ok(executeService.handle(id, conditionValue, message));
        } catch (Exception e) {
            String msg = MessageUtils.message("controller.handle");
            logger.error(msg, e);
            return R.fail(ExceptionUtil.handleMsg(msg, e));
        }
    }
}
